import { useEffect } from 'react'
import { ConfigProvider } from 'antd-mobile'
import { Provider, observer, useLocalObservable } from 'mobx-react'
import globalStore from '@/stores/globalStore'
import zhCN from 'antd-mobile/es/locales/zh-CN'
import changeTheme from '@/utils/changeTheme'
import * as Storage from '@/storage'
import { toJS } from 'mobx'
import type { IRoute } from 'umi'
import { useLocation } from 'umi'
import 'antd-mobile-v2/dist/antd-mobile.less'
import { setCookie, setLocalStorage } from '@/storage'

const stores = globalStore()

const GlobalLayout = observer((props: IRoute) => {
    const { userStore } = stores
    const store = useLocalObservable(() => userStore)
    const { loginQuick, teacherLoginQuick, visitorLoginQuick, hasToken, changeHasToken } = store
    /**刷新时同步本地user数据到store */
    const localUserToStore = () => {
        // const { userStore } = stores
        const { userData, update_user } = toJS(userStore)
        if (Object.keys(userData).length === 0) {
            const localUserData = Storage.getLocalStorage('USER_DATA')
            if (Object.prototype.toString.call(localUserData) === '[object Object]' && Object.keys(localUserData).length !== 0) {
                update_user(localUserData)
            }
        }
    }
    /**刷新时同步本地site数据到store */
    const localSiteToStore = () => {
        const { siteStore } = stores
        const { siteData, updateSiteData } = toJS(siteStore)
        if (Object.keys(siteData).length === 0) {
            const localSiteData = Storage.getLocalStorage('SITE_DATA')
            if (Object.prototype.toString.call(localSiteData) === '[object Object]' && Object.keys(localSiteData).length !== 0) {
                updateSiteData(localSiteData)
            } else {
                // getSiteData()
            }
        }
    }
    // identity_type 1:学生，2:讲师
    const {
        query: { token, platform_token, accessToken, domain, side_type, identity_type = 1, callback_url, skip_url, ...restQuery },
    }: any = useLocation()
    /** 免登白名单：PC拍卖相关 */
    const noLoginWhiteList = ['/auctionmanage']
    const { href } = window.location

    useEffect(() => {
        if (token) {
            async function tokenInfo() {
                setCookie('TOKEN', token)
                await store.getUserInfo()
                const user_data = { ...store.userData, access_token: token }
                Storage.setLocalStorage('USER_DATA', user_data)
                store.update_user(user_data)
                changeHasToken(true)
            }
            tokenInfo()
        }

        if (platform_token) {
            setCookie('PLATFORMTOKEN', platform_token)
        }

        localUserToStore()
        localSiteToStore()
        changeTheme({
            primaryColor: '#4462D2',
        })
        // 有返回地址设置返回地址
        if (callback_url) {
            setLocalStorage('CALLBACK_URL', decodeURIComponent(callback_url))
        }
        // 有额外跳转地址设置跳转地址
        if (skip_url) {
            setLocalStorage('SKIP_URL', decodeURIComponent(skip_url))
        }
        if (accessToken && domain) {
            setCookie('MLHTOKEN', accessToken)
            if (Number(identity_type) === 2) {
                Storage.setLocalStorage('IDENTITY_TYPE', 2)
                teacherLoginQuick({ access_token: accessToken, domain, side_type: side_type, ...restQuery })
            } else {
                if (Number(side_type) === 1 && !restQuery.group_id) {
                    visitorLoginQuick({
                        access_token: accessToken,
                        domain,
                        side_type: side_type,
                        ...restQuery,
                    })
                } else {
                    Storage.setLocalStorage('IDENTITY_TYPE', 1)
                    loginQuick({
                        access_token: accessToken,
                        domain,
                        side_type: side_type,
                        ...restQuery,
                    })
                }
            }
        } else {
            changeHasToken(true)
        }
    }, [])

    return hasToken || noLoginWhiteList.filter(url => href.includes(url)).length > 0 ? (
        <Provider {...stores}>
            <ConfigProvider locale={zhCN}>{props.children}</ConfigProvider>
        </Provider>
    ) : null
})

export default GlobalLayout
